﻿using System;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using KewlStuff.Extensions;
using MovieBuddy.Dialogs;
using MovieBuddy.Helpers;
using MovieModel.Model;
using MovieModel.Model.Common;

namespace MovieBuddy.Views
{
    /// <summary>
    /// Interaction logic for MovieDetailPanel.xaml
    /// </summary>
    public partial class MovieDetailPanel : UserControl
    {
        private const int ProperWidth = 228;

        private readonly EventHandler<ItemUpdatedEventArgs<MovieItem<Movie>>> movieUpdateHandler;

        public MovieDetailPanel()
        {
            InitializeComponent();
            Movies = null; // clear it out to hide the design time stuff.

            movieUpdateHandler = MovieUpdated;
        }

        public Manager Manager { get; set; }

        private Movie[] movies;

        public Movie[] Movies
        {
            get { return movies; }
            set
            {
                if (movies != null)
                {
                    foreach (var movie in movies)
                    {
                        movie.ItemUpdated -= movieUpdateHandler;
                    }
                }
                movies = value;
                if (movies != null)
                {
                    foreach (var movie in movies)
                    {
                        movie.ItemUpdated += movieUpdateHandler;
                    }
                }

                SetFields();
            }
        }

        private void SetFields()
        {
            image.Source = null;
            if (movies == null || movies.Length == 0)
            {
                Visibility = Visibility.Hidden;
                return;
            }
            var movie = movies[0];
            if (movie.ImageLocation != null)
            {
                try
                {
                    textArea.Width = ProperWidth;
                    image.Visibility = Visibility.Visible;
                    image.Source = ImageCache.GetImage(movie.ImageLocation);
                }
                catch
                {
                    try
                    {
                        image.Source = ImageCache.GetImage(movie.ThumbnailLocation);
                        
                    }
                    catch
                    {
                        image.Visibility = Visibility.Hidden;
                    }
                }
            }
            else
            {
                image.Visibility = Visibility.Collapsed;
                textArea.Width = Double.NaN;
            }
            SetText(title, movie.Name);
            SetText(year, movie.Year == null ? "" : "(" + movie.Year + ")");
            SetText(runtime, movie.Runtime == null ? "" : movie.Runtime + " minutes");
            SetText(description, movie.Description);
            SetText(companies, movie.Companies.JoinString(", "));
            SetText(tags, movie.Tags.JoinString(", "));
            SetText(people, movie.People.Select(p => p.Person).JoinString(", "));

            // ReSharper disable PossibleUnintendedReferenceComparison
            if (movies.Length == 1)
            {
                if (primaryParagraph.NextBlock == alsoSelectedParagraph)
                {
                    flowDocument.Blocks.Remove(alsoSelectedParagraph);
                }
            }
            else
            {
                if (primaryParagraph.NextBlock != alsoSelectedParagraph)
                {
                    flowDocument.Blocks.InsertAfter(primaryParagraph, alsoSelectedParagraph);
                }
                SetText(alsoSelected, movies.Skip(1).JoinString(", "));
            }
            // ReSharper restore PossibleUnintendedReferenceComparison

            Visibility = Visibility.Visible;
        }

        void MovieUpdated(object sender, ItemUpdatedEventArgs<MovieItem<Movie>> e)
        {
            Dispatcher.Invoke(SetFields);
        }

        static void SetText(Span span, string text)
        {
            span.Inlines.Clear();
            if (!string.IsNullOrEmpty(text)) span.Inlines.Add(text);
        }

        private void EditClicked(object sender, RoutedEventArgs e)
        {
            var dialog = new NewMovieDialog(Manager, Movies[0]);
            dialog.Show();
        }

        private void PlayClicked(object sender, RoutedEventArgs e)
        {
            PlaylistDialog.Instance.PlayMovies(movies);
        }

        private void EnqueueClicked(object sender, RoutedEventArgs e)
        {
            PlaylistDialog.Instance.EnqueueMovies(movies);
        }

        private void DeleteClicked(object sender, RoutedEventArgs e)
        {
            string name;
            if (Movies.Count() == 1)
            {
                name = Movies[0].Name;
            }
            else
            {
                name = Movies.Count() + " movies";
            }
            if (MessageBoxResult.OK ==
                MessageBox.Show(Window.GetWindow(this),
                    "Are you sure you want to delete " + name + "?", "Delete Confirmation",
                    MessageBoxButton.OKCancel))
            {
                foreach (Movie m in Movies)
                {
                    Manager.DeleteMovie(m);
                }
            }
        }
    }
}
